package cn.tedu.commons.security;

import cn.tedu.commons.response.JsonResult;
import cn.tedu.commons.response.ServiceCode;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.FilterChain;
import java.io.IOException;
import java.util.List;

@Component

public class JwtAuthenticationFilter extends OncePerRequestFilter {
    //Token 密匙
    private String secretKey = "jfdsfdslkjafdslkjafds";


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //从客户端中获取名为AUthentication的数据
        String jwt = request.getHeader("Authentication");
        System.out.println(jwt);
        if (!StringUtils.hasText(jwt)) {
            //判断是否获取到了数据
            //不存在有效的jwt数据，直接放行
            //由于某些请求本身也不要求登录，没有jwt数据是正常表现。
            //继续执行后面的过滤器链
            System.out.println("没有获取到jwt,直接放行");
            filterChain.doFilter(request, response);
            return;
        }
        //如果代码执行到此处，表示从请求头中获取到了疑似有效的jwt
        System.out.println("准备解析jwt");
        String username = null;
        try {
            JwtParser parser = Jwts.parser();
            Claims claims = parser.setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
            username = claims.get("username").toString();
            System.out.println("从jwt中解析username");
        } catch (SignatureException e) {
            System.out.println("解析失败，jwt数据有误");
            JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.FORBIDDEN, "jwt数据解析有误");
            String jsonResultString = JSON.toJSONString(jsonResult);
            response.setContentType("application/json; charset=utf-8");
            response.getWriter().println(jsonResultString);
            return;
        } catch (MalformedJwtException e) {
            System.out.println("解析失败，JWT数据有误");
            JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.FORBIDDEN, "JWT数据格式有误！");
            String jsonResultString = JSON.toJSONString(jsonResult);
            response.setContentType("application/json; charset=utf-8");
            response.getWriter().println(jsonResultString);
            return;
        } catch (ExpiredJwtException e) {
            System.out.println("解析失败，JWT数据已过期");
            JsonResult<Void> jsonResult = JsonResult.fail(ServiceCode.FORBIDDEN, "JWT数据已经过期！");
            String jsonResultString = JSON.toJSONString(jsonResult);
            response.setContentType("application/json; charset=utf-8");
            response.getWriter().println(jsonResultString);
            return;
        }
        // 将解析成功的JWT放回到Spring Security中

    }
}
